<script setup>
import {changePasswordApi} from "@/apis";
import {onMounted, reactive} from "vue";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import {useRoute} from "vue-router";
const route = useRoute();
const router = useRouter();
let changeWord=reactive({
  account:null,
  newWord:null,
  confirmPassword:null
})
let reset = async () => {
  changeWord.newWord=null;
  changeWord.confirmPassword=null;
}
onMounted(()=>{
  reset()
})
async function onClick(){
  changeWord.account = route.query.account;
  console.log(changeWord)
  let re = await changePasswordApi(changeWord);
  if (re === true) {
    ElMessage.success('修改成功');
    await router.push({name: 'selectCourse',query:{account:changeWord.account}})
  } else {
    ElMessage.error('修改失败');
  }
}
const validatePassword = (rule, value, callback) => {
  const hasNumber = /\d/.test(value);
  const hasLetter = /[a-zA-Z]/.test(value);
  const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(value);
  if (!hasNumber || !hasLetter || !hasSpecialChar) {
    return callback(new Error('密码必须包含数字、字母和特殊字符'));
  }
  if (value.length < 8) {
    return callback(new Error('密码长度必须大于7位'));
  }
  callback();
};

const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请确认新密码'));
  }
  if (value !== changeWord.newWord) {
    return callback(new Error('两次输入的密码不一致'));
  }
  callback();
};

const rules= {
  newPassword: [{ validator: validatePassword, trigger: 'blur' }],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }]
}
</script>

<template>
  <el-form :model="changeWord" :rules="rules" label-width="120px" class="custom-form">
    <el-form-item label="新密码" prop="newPassword" class="custom-form-item">
      <el-input v-model="changeWord.newWord" type="password" class="custom-input" show-password></el-input>
    </el-form-item>
    <el-form-item label="确认新密码" prop="confirmPassword" class="custom-form-item">
      <el-input v-model="changeWord.confirmPassword" type="password" class="custom-input" show-password></el-input>
    </el-form-item>
    <el-form-item class="custom-form-item">
      <el-button type="primary" @click="onClick" class="custom-button">提交</el-button>
      <el-button @click="reset" class="custom-button">重置</el-button>
    </el-form-item>
  </el-form>

</template>

<style scoped>
.custom-form {
  max-width: 400px;
  margin: 50px auto;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.custom-form-item {
  margin-bottom: 20px;
}

.custom-input {
  width: 100%;
}

.custom-button {
  margin-right: 10px;
}

</style>
